package org.ccay.web.support.listener;

import java.nio.charset.Charset;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.ccay.core.dispatcher.EventUtil;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.Application;
import org.ccay.core.server.IAfterStartupHandler;
import org.ccay.core.server.IBeforeShutdownHandler;
import org.ccay.core.server.IBeforeStartupHandler;
import org.ccay.core.util.StringUtil;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * 上下文初始化Listener	
 */
public class CcayApplicationContextListener implements ServletContextListener {
	private static final ILogger log = CcayLoggerFactory.getLogger("ccay");
	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {	
		//触发关闭前事件
		EventUtil.dispatch(IBeforeShutdownHandler.class);
		log.info("[重要信息] 应用正在停止，I will be back. I hope to see you soon.");
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent event) {		
		EventUtil.dispatch(IBeforeStartupHandler.class);		
		ConfigurableEnvironment contextEnv =(ConfigurableEnvironment)Ccay.getContext().getEnvironment();		
		String env = contextEnv.getActiveProfiles()[0];
		String network = event.getServletContext().getInitParameter("network");
		if(StringUtil.isNullOrEmpty(network)){
		    log.warn("Network not configured in web.xml. [intranet] will be used as default."); 
		    network = "intranet";
		    throw new RuntimeException("Network not configured in web.xml.");
		}
		log.info("Current Profile:" + env);
		log.info("Current network:" + network); 
		log.info("Default File Encode:" + System.getProperties().getProperty("file.encoding")); 
		log.info("Default Charset:" + Charset.defaultCharset()); 
		//设置当前环境，供公共服务使用
		Application app = (Application)Application.getCurrent();
		app.setNetwork(network);
		
		//触发启动后事件
		EventUtil.dispatch(IAfterStartupHandler.class);
		log.info("[重要信息] 您的应用 "+ app.getAppName() +" 启动完成，祝您的应用运行愉快！如果应用无法访问，请仔细检查上面的日志，以确认启动过程中是否发生了异常。");
	}
}
